import countryLanguage from './language';

const defaultCountryCode = '+86';

/**
 * @param {*} data // 国家数据
 * @param {*} code // 代码
 */

function getCountryForCode(languageKey: string, code: string) {
  // 取前两位
  let countryValue = null;
  const data = countryLanguage[languageKey]
    || countryLanguage[languageKey.slice(0, 2)]
    || countryLanguage.en;
  data.forEach((item: any) => {
    const value = item.data.find(
      (subItem: any) => subItem.countryCode === code
    );
    if (value) {
      countryValue = value;
    }
  });
  return countryValue;
}

function getCountryData(languageKey: string) {
  const languageJson = countryLanguage[languageKey]
    || countryLanguage[languageKey.slice(0, 2)]
    || countryLanguage.en;
  return languageJson;
}

function getCountryDataByCodes(languageKey: string, codes: string[]) {
  let languageJson = countryLanguage[languageKey]
    || countryLanguage[languageKey.slice(0, 2)]
    || countryLanguage.en;
  // 深拷贝，否则会影响原来的数据
  const result = JSON.parse(JSON.stringify(languageJson))
  return result.map(c => {
    c.data = c.data?.filter(item => {
      return codes.includes(item.countryCode)
    });
    return { ...c, data: c.data }
  }).filter(c => c.data.length)
}

function getCountryForPhoneCode(languageKey: string, phoneCode: string) {
  let countryValue = null;
  const data = countryLanguage[languageKey]
    || countryLanguage[languageKey.slice(0, 2)]
    || countryLanguage.en;
  data.forEach((item: any) => {
    const value = item.data.find(
      (subItem: any) => subItem.phoneCode === phoneCode
    );
    if (value) {
      countryValue = value;
    }
  });
  return countryValue;
}

export { getCountryForCode, getCountryData, getCountryForPhoneCode, getCountryDataByCodes, defaultCountryCode };
